package cn.uncode.springcloud.admin.service.eureka;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration;
import org.springframework.stereotype.Component;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;

import cn.uncode.springcloud.admin.model.eureka.EurekaInstanceBo;
import cn.uncode.springcloud.starter.boot.app.AppInfo;

@Component
public class EurekaService {
	
	@Resource
	private ServiceRegistry<EurekaRegistration> serviceRegistry;
	
	@Resource
	private EurekaRegistration registration;
	
	@Resource
	private EurekaClient eurekaClient;
	
	public List<EurekaInstanceBo> getAllApps() {
		List<EurekaInstanceBo> rtlist = new ArrayList<>();
		List<Application> apps = eurekaClient.getApplications().getRegisteredApplications();
		Collections.sort(apps, new Comparator<Application>() {
	        public int compare(Application l, Application r) {
	            return l.getName().compareTo(r.getName());
	        }
	    });
		for(Application app : apps){
			Collections.sort(app.getInstances(), new Comparator<InstanceInfo>() {
		        public int compare(InstanceInfo l, InstanceInfo r) {
		            return l.getPort() - r.getPort();
		        }
		    });
		}
		int id = 1;
		for(Application app : apps){
			List<InstanceInfo> instances = app.getInstancesAsIsFromEureka();
			for(InstanceInfo instance : instances){
				EurekaInstanceBo bo = new EurekaInstanceBo();
				bo.setName(app.getName());
				bo.setStatus(instance.getStatus().name());
				bo.setCanaryFlag(instance.getMetadata().get("canaryFlag")==null?"":instance.getMetadata().get("canaryFlag"));
				bo.setInstanceId(instance.getId());
				bo.setIpAddr(instance.getIPAddr());
				bo.setLastUpdatedTime(instance.getLastUpdatedTimestamp());
				bo.setStatusPageUrl(instance.getStatusPageUrl());
				bo.setPort(instance.getPort()+"");
				bo.setId(id);
				rtlist.add(bo);
				id++;
			}
		}
		
		return rtlist;
	}
	
	public void updateStatus(String appName, String instanceId, String status) {
		//http://localhost:1001/eureka/apps/UNCODE-ADMIN/DESKTOP-JL9T2IK:uncode-admin:8000/status?value=DOWN
		String url = AppInfo.getEnv().getProperty("eureka.client.serviceUrl.defaultZone");
		String[] ruls = url.split(",");
		String path = ruls[0].replaceAll("uncode:admin@", "");
		path = path + "/apps/" + appName + "/" + instanceId + "/status?value=" + status;
		InputStream is = null;
        BufferedReader br = null;
        StringBuilder sBuilder = null;
		try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPut httpPut = new HttpPut(path);
            httpPut.addHeader("Content-Type", "text/plain");
            HttpResponse httpResponse = httpClient.execute(httpPut);
            //连接成功
            if(200 == httpResponse.getStatusLine().getStatusCode()){
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                br = new BufferedReader(new InputStreamReader(is));
                String tempStr;
                sBuilder = new StringBuilder();
                while ((tempStr = br.readLine()) != null) {
                    sBuilder.append(tempStr);
                }
                br.close();
                is.close();
            }
        }catch (Exception e){
            System.out.println(e);
            e.printStackTrace();
        }
	}

}
